package com.gao.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gao.dao.ProductDao;
import com.gao.domain.Product;
import com.gao.util.DBUtil;

public class ProductDaoImpl implements ProductDao{

	@Override
	public List<Product> findAllProducts()  throws SQLException{
		List<Product> products = new ArrayList<Product>();
		Connection conn = DBUtil.getConnection();
		String sql = "select * from product";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			products.add(new Product(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getDouble(5),rs.getInt(6)));
		}
		DBUtil.release(rs,pstmt, conn);
		return products;
	}

	@Override
	public Product findProductById(int id)  throws SQLException{
		Product product = null;
		Connection conn = DBUtil.getConnection();
		String sql = "select * from product where pid=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, id);
		ResultSet rs = pstmt.executeQuery();
		if(rs.next()){
			product = new Product(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getDouble(5),rs.getInt(6));
		}
		DBUtil.release(rs,pstmt, conn);
		return product;
	}

	@Override
	public boolean inProductById(int id, int num)  throws SQLException{
		return false;
	}

	@Override
	public boolean outProductById(int pid, int num) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "update product set num=num-? where pid=? ";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, num);
		pstmt.setInt(2, pid);
		int numRow = pstmt.executeUpdate();
		DBUtil.release(pstmt, conn);
		return numRow>1;
	}
	
}
